<template>
  <div>
    <div class="form-header">
      <span v-if="type == 'create'"> 添加客户 </span>
      <div>
        <el-button type="success" @click="save" :loading="saveLoading"
        >保存</el-button
      >
      <el-button type="success" @click="tongbu" :loading="tongbuLoading"
        >同步</el-button
      >
      </div>
     
    </div>
    <div class="gva-form-box">
      <div class="form-box">
        <el-form
          :model="formData"
          ref="elFormRef"
          label-position="right"
          :rules="rule"
          label-width="120px"
        >
          <el-form-item label="客户编号:" prop="customerNum">
            <el-input
              v-model="formData.customerNum"
              :clearable="true"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="客户名称:" prop="member">
            <el-input
              v-model="formData.customerName"
              :clearable="true"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="客户品牌:" prop="brandDatas">
            <el-table :data="formData.brandDatas" style="width: 100%" border>
              <el-table-column label="品牌名称">
                <template #default="{ row }">
                  <el-input
                    v-model="row.brandName"
                    :clearable="true"
                    placeholder="请输入"
                  />
                </template>
              </el-table-column>
              <el-table-column width="80">
                <template #header>
                  <el-icon
                    @click="handleAdd(row)"
                    style="cursor: pointer; color: skyblue; font-size: 22px"
                    ><CirclePlusFilled
                  /></el-icon>
                </template>
                <template #default="{ row, $index }">
                  <el-icon
                    @click="handleDel(row, $index)"
                    style="cursor: pointer; color: red; font-size: 22px"
                    ><RemoveFilled
                  /></el-icon>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

        <el-form-item label="走地:" prop="groundDatas">
          <el-table :data="formData.groundDatas" style="width: 100%" border>
            <el-table-column label="走地名称">
              <template #default="{ row }">
                <el-input
                  v-model="row.groundName"
                  :clearable="true"
                  placeholder="请输入"
                />
              </template>
            </el-table-column>
            <el-table-column width="80">
              <template #header>
                <el-icon
                  @click="handleAdd2(row)"
                  style="cursor: pointer; color: skyblue; font-size: 22px"
                  ><CirclePlusFilled
                /></el-icon>
              </template>
              <template #default="{ row, $index }">
                <el-icon
                  @click="handleDel2(row, $index)"
                  style="cursor: pointer; color: red; font-size: 22px"
                  ><RemoveFilled
                /></el-icon>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="印资种类:" prop="printingTypes">
          
          <el-table :data="formData.printingTypes" style="width: 100%" border>
            <el-table-column label="印资种类">
              <template #default="{ row }">
                <el-input
                  v-model="row.printingName"
                  :clearable="true"
                  placeholder="请输入"
                />
              </template>
            </el-table-column>
            <el-table-column width="80">
              <template #header>
                <el-icon
                  @click="handleAdd3(row)"
                  style="cursor: pointer; color: skyblue; font-size: 22px"
                  ><CirclePlusFilled
                /></el-icon>
              </template>
              <template #default="{ row, $index }">
                <el-icon
                  @click="handleDel3(row, $index)"
                  style="cursor: pointer; color: red; font-size: 22px"
                  ><RemoveFilled
                /></el-icon>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
defineOptions({
  name: "sbuDataAdd",
});

// 自动获取字典
import { getDictFunc } from "@/utils/format";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { ref, reactive } from "vue";
import { emitter } from "@/utils/bus.js";

import { getUserList } from "@/api/user";
import {
  createCustomerInfo,
  updateCustomerInfo,
  findCustomerInfo,
  syncCustomerInfo,
} from "@/api/confCustomerInfo";
import { getBrandDataList } from "@/api/confBrandData";

const route = useRoute();
const router = useRouter();

const type = ref("");
const formData = ref({
  customerNum: "",
  customerName: "",
  brandDatas: [],
  printingTypes:[],
  groundDatas:[],
});
const saveLoading = ref(false);
const tongbuLoading = ref(false);
const brandListOptions = ref([]); // 品牌列表

// 验证规则
const rule = reactive({
  customerNum: [{ required: true, message: "请输入客户编号", trigger: "blur" }],
  customerName: [
    { required: true, message: "请输入客户名称", trigger: "blur" },
  ],
  // brandDatasStr: [
  //     { required: true, message: "请输入客户品牌", trigger: "blur" },
  // ],
});

const elFormRef = ref();

// // 获取品牌列表
// const getBrandList = async (keyword) => {
//     const table = await getBrandDataList({
//         page: 1,
//         pageSize: 100,
//         brandName: keyword,
//     });
//     if (table.code === 0) {
//         brandListOptions.value = table.data.list.concat(
//             formData.value.brandDatas
//         );
//     }
// };

// 初始化方法
const init = async () => {
  // 建议通过url传参获取目标数据ID 调用 find方法进行查询数据操作 从而决定本页面是create还是update 以下为id作为url参数示例
  if (route.query.id) {
    const res = await findCustomerInfo({ ID: route.query.id });
    if (res.code === 0) {
      formData.value = res.data.recustomerInfo;
      type.value = "update";
      // brandListOptions.value = res.data.recustomerInfo.brandDatas;
    }
  } else {
    type.value = "create";
  }
};

const handleAdd = (row) => {
  formData.value.brandDatas.push({
    brandNum: "",
    brandName: "",
  });
};
const handleDel = (row, index) => {
  formData.value.brandDatas.splice(index, 1);
};

const handleAdd2 = (row) => {
  formData.value.groundDatas.push({
    groundNum: "",
    groundName: "",
    // isDeleted:'0',
    // customerNum: formData.value.customerNum
  });
};
const handleDel2 = (row, index) => {
  formData.value.groundDatas.splice(index, 1);
};

const handleAdd3= (row) => {
  formData.value.printingTypes.push({
    printingNum: "",
    printingName: "",
  });
};
const handleDel3 = (row, index) => {
  formData.value.printingTypes.splice(index, 1);
};

init();
// 保存按钮
const save = () => {
  elFormRef.value?.validate(async (valid) => {
    if (!valid) return;
    let res;
    saveLoading.value = true;
    let brandDatas = formData.value.brandDatas.map((item) => {
      let obj1 = {
        brandName: item.brandName,
        brandNum: item.brandNum,
        customerNum: formData.value.customerNum,
      };
      if (item.ID) obj["ID"] = item.ID;
      return obj1;
    });
    let obj1 = {};
    for (let i = 0; i < brandDatas.length; i++) {
      if (
        brandDatas[i].brandName == undefined ||
        brandDatas[i].brandName == ""
      ) {
        ElMessage({
          type: "warning",
          message: "品牌名称不能为空",
        });
        saveLoading.value = false;
        return;
      }
      if (obj1[brandDatas[i].brandName]) {
        ElMessage({
          type: "warning",
          message: "品牌名称不能重复",
        });
        saveLoading.value = false;
        return;
      }
      obj1[brandDatas[i].brandName] = 1;
    }

    let groundDatas = formData.value.groundDatas.map((item) => {
      let obj2 = {
        groundName: item.groundName,
        groundNum: item.groundNum,
        customerNum: formData.value.customerNum,
      };
      if (item.ID) obj2["ID"] = item.ID;
      return obj2;
    });
    let obj2 = {};
    for (let i = 0; i < groundDatas.length; i++) {
      if (
        groundDatas[i].groundName == undefined ||
        groundDatas[i].groundName == ""
      ) {
        ElMessage({
          type: "warning",
          message: "走地名称不能为空",
        });
        saveLoading.value = false;
        return;
      }
      if (obj2[groundDatas[i].groundName]) {
        ElMessage({
          type: "warning",
          message: "走地名称不能重复",
        });
        saveLoading.value = false;
        return;
      }
      obj2[groundDatas[i].groundName] = 1;
    }

    let printingTypes = formData.value.printingTypes.map((item) => {
      let obj3 = {
        printingName: item.printingName,
        printingNum: item.printingNum,
        customerNum: formData.value.customerNum,
      };
      if (item.ID) obj3["ID"] = item.ID;
      return obj3;
    });
    let obj3 = {};
    for (let i = 0; i < printingTypes.length; i++) {
      if (
        printingTypes[i].printingName == undefined ||
        printingTypes[i].printingName == ""
      ) {
        ElMessage({
          type: "warning",
          message: "印资种类不能为空",
        });
        saveLoading.value = false;
        return;
      }
      if (obj3[printingTypes[i].printingName]) {
        ElMessage({
          type: "warning",
          message: "印资种类不能重复",
        });
        saveLoading.value = false;
        return;
      }
      obj3[printingTypes[i].printingName] = 1;
    }

    let submitForm = {
      ID: formData.value.ID,
      customerNum: formData.value.customerNum,
      customerName: formData.value.customerName,
      brandDatas: brandDatas,
      printingTypes,
      groundDatas,
    };
    switch (type.value) {
      case "create":
        res = await createCustomerInfo(submitForm);
        emitter.emit("closeThisPage");
        break;
      case "update":
        res = await updateCustomerInfo(submitForm);
        init();
        break;
      default:
        res = await createCustomerInfo(submitForm);
        break;
    }
    saveLoading.value = false;

    if (res.code === 0) {
      ElMessage({
        type: "success",
        message: type.value == "create" ? "创建成功" : "更改成功",
      });
    }
  });
};

const tongbu = async () => {
  elFormRef.value?.validate(async (valid) => {
    if (!valid) return;
    let res;
    tongbuLoading.value = true;

    res = await syncCustomerInfo({
      customerNum: formData.value.customerNum,
    });

    tongbuLoading.value = false;

    if (res.code === 0) {
      ElMessage({
        type: "success",
        message:  "同步成功" ,
      });
      init();
    }
  });
};

// 返回按钮
const back = () => {
  router.go(-1);
};
</script>

<style lang="scss" scoped>
.form-header {
  font-size: 22px;
  font-weight: 600;
  background: #fff;
  padding: 20px;
  border-bottom: 1px solid #ccc5;
  display: flex;
  justify-content: space-between;
}
.form-box {
  width: 45%;
  margin: 0 auto;
}
.form-footer {
  text-align: center;
}
</style>
